package is.common.watchdog;

import is.common.interfaces.DeactivationNeededThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.LinkedList;

/**
 * @author aspr0
 *         Date: 27.04.12
 *         Time: 22:45
 */
public class WatchdogServerThread extends WatchdogAbstractThread implements DeactivationNeededThread
{
    private ServerSocket serverSocket;
    private LinkedList<WatchdogServerSessionThread> sessionsList = new LinkedList<WatchdogServerSessionThread>();

    private boolean watching = true;

    public WatchdogServerThread(int port) throws IOException
    {
        super();
        serverSocket = new ServerSocket(port);
    }

    @Override
    public void run()
    {
        while (watching)
        {
            try
            {
                sessionsList.add(new WatchdogServerSessionThread(serverSocket.accept()));
                sessionsList.getLast().start();
            }
            catch (IOException e)
            {
//                e.printStackTrace();
            }
        }
    }

    @Override
    public void deactivate() throws IOException
    {
        watching = false;
        serverSocket.setSoTimeout(0);

        while (sessionsList.size() > 0)
        {
            /* removing last client from list and deactivating his session */
            sessionsList.removeLast().deactivate();
        }

        serverSocket.close();
    }
}
